package com.sisyphe.android.srouter.proxy

import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy

fun main(args: Array<String>) {
    val movable = Tank()
    val o = Proxy.newProxyInstance(Movable::class.java.classLoader, arrayOf(Movable::class.java), ProxyTank(movable)) as Movable
    o.move("Di Di")
}

interface Movable {
    fun move(key: String)
}

class Tank : Movable {
    override fun move(key: String) {
        println("Tank moving -> $key")
    }
}

class Car : Movable {
    override fun move(key: String) {
        println("Car moving -> $key")
    }
}

class ProxyTank(private val movable: Movable) : InvocationHandler {

    @Throws
    override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any? {
//        println("Before ${method?.name} invoke")
        val invoke = if (true == args?.isNotEmpty()) {
            method?.invoke(movable, *args)
        } else {
            method?.invoke(movable)
        }
//        println("After ${method?.name} invoke")
        return invoke
    }
}